package lormi.meipin.service.impl;

import lormi.meipin.common.LMYunTongXunAPI;
import lormi.meipin.dto.CheckCodeDto;
import lormi.meipin.entity.CheckCode;
import lormi.meipin.entity.Location;
import lormi.meipin.entity.LocationLog;
import lormi.meipin.entity.LoginLog;
import lormi.meipin.exception.LMException;
import lormi.meipin.service.BaseService;
import lormi.meipin.service.ICheckCodeService;
import lormi.meipin.service.IMemberService;
import lormi.meipin.util.CacheUtil;
import lormi.meipin.util.DateUtil;
import lormi.meipin.util.StringUtil;
import lormi.meipin.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * 短信接口
 * 
 * @author ThreeFeng
 * @date 2016年8月12日 下午5:46:13
 */
@Service
public class CheckCodeService extends BaseService implements ICheckCodeService {

	@Autowired
	private IMemberService memberService;

	@Override
	public void sendPhoneCode(String phone) throws LMException{
		String code = LMYunTongXunAPI.getPhoneCode();
		LMYunTongXunAPI.sendPhone(phone, code);
		
		CheckCode checkCode = checkCodeMapper.selectByPhone(phone);
		if (checkCode==null){
			checkCodeMapper.insert(new CheckCode(phone,Integer.valueOf(code)));
		}else{
			checkCode.setCode(Integer.valueOf(code));
			checkCode.setCreatetime(new Date());
			checkCodeMapper.update(checkCode);
		}
	}

	@Override
	@Transactional
	public LoginVo checkCodeValid(CheckCodeDto checkCodeDto) throws LMException {
		checkCodeVaild(checkCodeDto.getPhone(),checkCodeDto.getCodeForInt());
		//3.判断用户是否存在，存在返回用户信息，否则返回验证正确信息
		LoginVo loginVo = memberService.checkMember(checkCodeDto.getPhone());
		
		//4.如果用户存在，则插入相关日志,如果邀请吗纪录邀请码
		if (loginVo!=null) {
			loginLogMapper.insert(new LoginLog(checkCodeDto,loginVo.getId()));
			locationMapper.insert(new Location(checkCodeDto,loginVo.getId(),loginVo.getUsertype()));
			locationLogMapper.insert(new LocationLog(checkCodeDto.getLongitude(),checkCodeDto.getLatitude(),loginVo.getId()));
		}else if (StringUtil.isNotNull(checkCodeDto.getInvitationcode())) {
			//5.如果用户不存在，判断邀请码是否存在
			//存在将邀请码先纪录到缓存中，在注册的时候插入数据库
			CacheUtil.getCacheUtil().setOtherCache("invite_"+checkCodeDto.getPhone(),checkCodeDto.getInvitationcode());
		}
		return loginVo;
	}
	
	@Override
	public void checkCodeVaild(String phone,Integer code) throws LMException{
		CheckCode checkCode = checkCodeMapper.selectByPhone(phone);
		if (checkCode==null) {
			throw new LMException(161003);
		}
		if (!checkCode.getCode().equals(code)) {
			throw new LMException(120004);
		}
		if (!DateUtil.checkDateisValid(checkCode.getCreatetime(), 5*60*1000)) {
			throw new LMException(120013);
		}
	}

}
